#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Elasticsearch配置管理
"""

import os
from typing import Dict, Any, Optional


class ElasticsearchConfig:
    """Elasticsearch配置管理器"""
    
    DEFAULT_CONFIG = {
        'es_host': 'https://localhost',
        'es_port': 9200,
        'es_user': 'elastic',
        'es_password': 'ncUg27UP5aMSzSElVXAX',
        'index_name': 'qwen_agent_docs',
        'verify_certs': False,
        'chunk_size': 500,
        'chunk_overlap': 50,
        'max_results': 5,
        'request_timeout': 60,
        'max_retries': 3,
        'retry_on_timeout': True
    }
    
    @classmethod
    def from_env(cls) -> Dict[str, Any]:
        """从环境变量加载配置"""
        config = cls.DEFAULT_CONFIG.copy()
        
        # 从环境变量覆盖配置
        env_mappings = {
            'ES_HOST': 'es_host',
            'ES_PORT': 'es_port',
            'ES_USER': 'es_user',
            'ES_PASSWORD': 'es_password',
            'ES_INDEX_NAME': 'index_name',
            'ES_VERIFY_CERTS': 'verify_certs',
            'ES_CHUNK_SIZE': 'chunk_size',
            'ES_CHUNK_OVERLAP': 'chunk_overlap',
            'ES_MAX_RESULTS': 'max_results'
        }
        
        for env_key, config_key in env_mappings.items():
            env_value = os.getenv(env_key)
            if env_value is not None:
                # 类型转换
                if config_key in ['es_port', 'chunk_size', 'chunk_overlap', 'max_results']:
                    config[config_key] = int(env_value)
                elif config_key in ['verify_certs']:
                    config[config_key] = env_value.lower() in ('true', '1', 'yes')
                else:
                    config[config_key] = env_value
        
        return config
    
    @classmethod
    def from_dict(cls, config_dict: Dict[str, Any]) -> Dict[str, Any]:
        """从字典加载配置"""
        config = cls.DEFAULT_CONFIG.copy()
        config.update(config_dict)
        return config
    
    @classmethod
    def get_connection_string(cls, config: Dict[str, Any]) -> str:
        """获取连接字符串"""
        return f"{config['es_host']}:{config['es_port']}"
    
    @classmethod
    def validate_config(cls, config: Dict[str, Any]) -> bool:
        """验证配置"""
        required_keys = ['es_host', 'es_port', 'es_user', 'es_password']
        
        for key in required_keys:
            if key not in config or not config[key]:
                return False
        
        return True


def get_default_config() -> Dict[str, Any]:
    """获取默认配置"""
    return ElasticsearchConfig.DEFAULT_CONFIG.copy()


def get_config_from_env() -> Dict[str, Any]:
    """从环境变量获取配置"""
    return ElasticsearchConfig.from_env()


def create_config(custom_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """
    创建配置
    
    Args:
        custom_config: 自定义配置
        
    Returns:
        合并后的配置
    """
    # 从环境变量加载基础配置
    config = ElasticsearchConfig.from_env()
    
    # 合并自定义配置
    if custom_config:
        config.update(custom_config)
    
    return config